// return_books.dart
import 'package:flutter/material.dart';
import 'storage_service.dart';
import 'models.dart';

class ReturnScreen extends StatefulWidget {
  @override
  _ReturnScreenState createState() => _ReturnScreenState();
}

class _ReturnScreenState extends State<ReturnScreen> {
  List<BorrowRecord> _overdueRecords = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadOverdueRecords();
  }

  Future<void> _loadOverdueRecords() async {
    try {
      setState(() => _isLoading = true);
      print('🔄 开始加载逾期记录');

      final rawRecords = await StorageService.loadBorrowRecords();
      print('✅ 加载完成，原始记录数: ${rawRecords.length}');

      // 打印原始数据用于调试
      print('🔍 原始借阅记录数据:');
      for (int i = 0; i < rawRecords.length; i++) {
        print('[$i]: ${rawRecords[i]}');
      }

      if (rawRecords.isEmpty) {
        setState(() {
          _overdueRecords = [];
          _isLoading = false;
        });
        print('ℹ️ 无借阅记录');
        return;
      }

      int startIndex = 0;
      if (rawRecords[0][0] == 'bookId') {
        startIndex = 1;
        print('📋 发现标题行');
      }

      List<BorrowRecord> allRecords = [];
      for (int i = startIndex; i < rawRecords.length; i++) {
        final row = rawRecords[i];

        if (row.length < 5) {
          print('⚠️ 行数据不完整，跳过: $row');
          continue;
        }

        try {
          // 解析日期 - 使用更简单的方法
          DateTime borrowDate = _parseDate(row[2].toString());
          DateTime dueDate = _parseDate(row[3].toString());

          // 创建记录对象
          final record = BorrowRecord(
            bookId: row[0].toString(),
            bookTitle: row[1].toString(),
            borrowDate: borrowDate,
            dueDate: dueDate,
            isReturned: (row[4].toString().toLowerCase() == 'true'),
          );

          allRecords.add(record);
          print('📝 添加记录: ${record.bookTitle} (借阅日期: ${borrowDate})');
        } catch (e) {
          print('❌ 创建记录失败: $e\n行数据: $row');
        }
      }

      // 筛选逾期记录
      final now = DateTime.now();
      final overdue = allRecords.where((r) {
        return !r.isReturned && r.dueDate.isBefore(now);
      }).toList();

      setState(() {
        _overdueRecords = overdue;
        _isLoading = false;
      });

      print('🔄 加载完成，逾期记录数: ${_overdueRecords.length}');
    } catch (e) {
      print('❌ 加载逾期记录失败: $e');
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('❌ 加载逾期记录失败: ${e.toString()}')));
    }
  }

  // 简化的日期解析方法
  DateTime _parseDate(String dateString) {
    try {
      // 尝试直接解析
      return DateTime.parse(dateString);
    } catch (e) {
      print('❌ 日期解析失败: $dateString, 使用当前时间代替');
      return DateTime.now();
    }
  }

  Future<void> _returnBook(BorrowRecord record) async {
    try {
      print('🔄 开始归还逾期图书: ${record.bookTitle} (唯一ID: ${record.uniqueId})');

      // 1. 加载所有记录
      List<List<dynamic>> records = await StorageService.loadBorrowRecords();
      print('🔍 加载记录成功，数量: ${records.length}');

      // 2. 找到并更新对应记录
      bool recordUpdated = false;

      for (int i = 0; i < records.length; i++) {
        // 跳过标题行
        if (i == 0 && records[i][0] == 'bookId') continue;

        // 确保行有足够的数据
        if (records[i].length < 5) continue;

        // 创建当前行记录的唯一ID
        final rowBookId = records[i][0].toString();
        DateTime rowBorrowDate = _parseDate(records[i][2].toString());

        final rowUniqueId = '$rowBookId-${rowBorrowDate.millisecondsSinceEpoch}';

        // 使用唯一ID进行比较
        if (rowUniqueId == record.uniqueId) {
          records[i][4] = 'true'; // 标记为已归还
          recordUpdated = true;
          print('🔄 找到并更新记录: ${record.bookTitle}');
          print('  记录唯一ID: $rowUniqueId');
          break;
        }
      }

      if (!recordUpdated) {
        // 尝试回退匹配方式
        bool fallbackUpdated = false;
        for (int i = 0; i < records.length; i++) {
          if (i == 0 && records[i][0] == 'bookId') continue;
          if (records[i].length < 5) continue;

          final rowBookId = records[i][0].toString();
          final rowBookTitle = records[i][1].toString();

          // 回退匹配：只比较ID和标题
          if (rowBookId == record.bookId && rowBookTitle == record.bookTitle) {
            records[i][4] = 'true';
            fallbackUpdated = true;
            print('⚠️ 使用回退方式更新记录: ${record.bookTitle}');
            break;
          }
        }

        if (!fallbackUpdated) {
          throw Exception('未找到对应的借阅记录: ${record.bookTitle} (唯一ID: ${record.uniqueId})');
        }
      }

      // 3. 保存更新后的记录
      await StorageService.saveBorrowRecords(records);
      print('💾 保存记录成功');

      // 4. 更新图书可借数量
      final book = allBooks.firstWhere(
            (b) => b.id == record.bookId,
        orElse: () {
          print('⚠️ 找不到对应图书: ID=${record.bookId}');
          return Book(
            id: record.bookId,
            title: record.bookTitle,
            author: '未知',
            coverUrl: '',
            description: '',
            isbn: '',
            publisher: '',
            publishYear: DateTime.now().year,
            totalCopies: 1,
            availableCopies: 0,
          );
        },
      );

      setState(() {
        book.availableCopies++;
        // 从逾期列表中移除记录
        _overdueRecords.removeWhere((r) => r.uniqueId == record.uniqueId);
      });

      print('📈 图书可借数量增加: ${book.availableCopies}');

      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('✅ 已归还《${record.bookTitle}》')));
    } catch (e) {
      print('❌ 归还逾期图书失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('❌ 归还失败: ${e.toString()}')));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('逾期图书')),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(
              "待归还图书 (${_overdueRecords.length})",
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Expanded(
            child: _overdueRecords.isEmpty
                ? RefreshIndicator(
              onRefresh: _loadOverdueRecords,
              child: SingleChildScrollView(
                physics: AlwaysScrollableScrollPhysics(),
                child: Center(
                  heightFactor: 10,
                  child: Text("无逾期图书"),
                ),
              ),
            )
                : RefreshIndicator(
              onRefresh: _loadOverdueRecords,
              child: ListView.builder(
                itemCount: _overdueRecords.length,
                itemBuilder: (context, index) => OverdueBookItem(
                  record: _overdueRecords[index],
                  onReturn: () => _returnBook(_overdueRecords[index]),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class OverdueBookItem extends StatelessWidget {
  final BorrowRecord record;
  final VoidCallback onReturn;

  const OverdueBookItem({
    Key? key,
    required this.record,
    required this.onReturn,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final daysOverdue = DateTime.now().difference(record.dueDate).inDays;

    return Card(
      color: Colors.red[50],
      margin: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: ListTile(
        leading: Icon(Icons.warning, color: Colors.red),
        title: Text(record.bookTitle),
        subtitle: Text("逾期 $daysOverdue 天"),
        trailing: ElevatedButton(
          onPressed: onReturn,
          child: Text("立即归还"),
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.red,
            foregroundColor: Colors.white,
          ),
        ),
      ),
    );
  }
}